package com.zmx.doctor.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.gyf.immersionbar.ImmersionBar;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.zmx.doctor.R;
import com.zmx.doctor.adapter.GoodsClassificationAdapter;
import com.zmx.doctor.adapter.MallGoodsAdapter;
import com.zmx.doctor.okhttp.OkHttp3ClientManager;
import com.zmx.doctor.pojo.BannerMessage;
import com.zmx.doctor.pojo.GoodsClassification;
import com.zmx.doctor.pojo.MallGoods;
import com.zmx.doctor.utils.AllUtil;
import com.zmx.doctor.view.activity.GoodsDetailsActivity;
import com.zmx.doctor.view.activity.GoodsItemActivity;
import com.zmx.doctor.view.activity.OrderManagementActivity;
import com.zmx.doctor.view.activity.ShoppingCartActivity;
import com.zmx.doctor.view.util.GlideImageLoader;
import com.zmx.doctor.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;


public class TwoFragment extends SimpleImmersionFragment implements View.OnClickListener {

    TextView logo;
    ImageView messageButton;
    ImageView goodsImageA;
    ImageView goodsImageB;
    ImageView goodsImageC;
    private GoodsClassificationAdapter adapter;
    private List<GoodsClassification> lists;

    private MallGoodsAdapter mgAdapter;
    private MallGoodsAdapter r_mgAdapter;
    private List<MallGoods> mallGoods;
    private List<MallGoods> r_Goods;
    private List<BannerMessage> bms;

    private RecyclerView grid_view;
    private RecyclerView r_View;
    private RecyclerView recyclerView;

    private Integer image_id_a,image_id_b,image_id_c;

    private Banner banner;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_two, container, false);

        logo = view.findViewById(R.id.logo);
        logo.setOnClickListener(this);
        messageButton = view.findViewById(R.id.message_button);
        messageButton.setOnClickListener(this);
        goodsImageA = view.findViewById(R.id.goods_image_a);
        goodsImageA.setOnClickListener(this);
        goodsImageB = view.findViewById(R.id.goods_image_b);
        goodsImageB.setOnClickListener(this);
        goodsImageC = view.findViewById(R.id.goods_image_c);
        goodsImageC.setOnClickListener(this);

        grid_view = view.findViewById(R.id.grid_view);
        LinearLayoutManager layout = new LinearLayoutManager(TwoFragment.this.getContext());
        layout.setOrientation(LinearLayoutManager.HORIZONTAL);//设置为横向排列
        grid_view.setLayoutManager(layout);
        lists = new ArrayList<>();
        adapter = new GoodsClassificationAdapter(TwoFragment.this.getActivity());
        grid_view.setAdapter(adapter);
        bms = new ArrayList<>();

        recyclerView = view.findViewById(R.id.recyclerView);
        mgAdapter = new MallGoodsAdapter(TwoFragment.this.getActivity());
        recyclerView.setLayoutManager(new GridLayoutManager(TwoFragment.this.getActivity(), 3));
        recyclerView.setAdapter(mgAdapter);
        mallGoods = new ArrayList<>();
        mgAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                Intent intent = new Intent(TwoFragment.this.getActivity(), GoodsDetailsActivity.class);
                intent.putExtra("goods_id", mallGoods.get(listPosition).getGoods_id() + "");
                startActivity(intent);
            }
        });

        r_View = view.findViewById(R.id.r_View);
        r_mgAdapter = new MallGoodsAdapter(TwoFragment.this.getActivity());
        LinearLayoutManager layouts = new LinearLayoutManager(TwoFragment.this.getContext());
        layouts.setOrientation(LinearLayoutManager.HORIZONTAL);//设置为横向排列
        r_View.setLayoutManager(layouts);
        r_View.setAdapter(r_mgAdapter);
        r_Goods = new ArrayList<>();
        r_mgAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                Intent intent = new Intent(TwoFragment.this.getActivity(), GoodsDetailsActivity.class);
                intent.putExtra("goods_id", r_Goods.get(listPosition).getGoods_id() + "");
                startActivity(intent);
            }
        });

        banner = view.findViewById(R.id.banner);

        getGroup();
        getCarousel();
        getActivitys();
        getIndex();
        getActivity_r();

        return view;
    }

    @Override
    public void initImmersionBar() {
        ImmersionBar.with(this).titleBarMarginTop(R.id.toolbar) .statusBarDarkFont(true).init();
    }



    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());

                        JSONArray data = object.getJSONArray("data");
                        Gson g = new Gson();
                        for (int i = 0; i < data.length(); i++) {

                            JSONObject jsonObject = data.getJSONObject(i);
                            GoodsClassification gc = g.fromJson(jsonObject.toString(), GoodsClassification.class);
                            lists.add(gc);

                        }

                        adapter.setListAndNotifyDataSetChanged(lists);


                    } catch (JSONException e) {
                        Log.e("异常", "异常" + e.toString());
                        e.printStackTrace();
                    }

                    break;

                case 2:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        JSONArray data = object.getJSONArray("data");
                        Gson g = new Gson();

                        for (int i = 0; i < data.length(); i++) {

                            JSONObject jsonObject = data.getJSONObject(i);
                            MallGoods gc = g.fromJson(jsonObject.toString(), MallGoods.class);
                            mallGoods.add(gc);

                        }

                        mgAdapter.setListAndNotifyDataSetChanged(mallGoods);

                    } catch (JSONException e) {
                        Log.e("异常", "异常" + e.toString());
                        e.printStackTrace();
                    }

                    break;

                case 3:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());

                        List<String> images = new ArrayList<>();
                        JSONArray data = object.getJSONArray("data");
                        Gson g = new Gson();
                        for (int i = 0; i < data.length(); i++) {

                            JSONObject jsonObject = data.getJSONObject(i);
                            BannerMessage gc = g.fromJson(jsonObject.toString(), BannerMessage.class);
                            bms.add(gc);
                            images.add(gc.getPicture());

                        }

                        //设置图片加载器😀+
                        banner.setImageLoader(new GlideImageLoader());
                        //设置图片集合
                        banner.setDelayTime(3000);
                        banner.setImages(images);
                        banner.setOnBannerListener(new OnBannerListener() {
                            @Override
                            public void OnBannerClick(int position) {

                                Intent intent = new Intent(TwoFragment.this.getActivity(), GoodsDetailsActivity.class);
                                intent.putExtra("goods_id", bms.get(position).getGoods_id() + "");
                                startActivity(intent);

                            }
                        });
                        //banner设置方法全部调用完毕时最后调用
                        banner.start();

                    } catch (JSONException e) {
                        Log.e("异常", "异常" + e.toString());
                        e.printStackTrace();
                    }

                    break;

                case 4:

                    Log.e("输出结果","输出"+msg.obj.toString());

                    try {
                        JSONObject object = new JSONObject(msg.obj.toString());
                        JSONArray data = object.getJSONArray("data");
                        Gson g = new Gson();

                        for (int i = 0; i < data.length(); i++) {

                            JSONObject jsonObject = data.getJSONObject(i);
                            MallGoods gc = g.fromJson(jsonObject.toString(), MallGoods.class);

                            if (i == 0) {

                                Glide.with(TwoFragment.this.getActivity()).load(gc.getImg()).into(goodsImageA);
                                image_id_a = gc.getGoods_id();
                            }else if (i == 1){

                                Glide.with(TwoFragment.this.getActivity()).load(gc.getImg()).into(goodsImageB);
                                image_id_b = gc.getGoods_id();

                            }else{
                                Glide.with(TwoFragment.this.getActivity()).load(gc.getImg()).into(goodsImageC);
                                image_id_c = gc.getGoods_id();
                            }


                        }


                    } catch (JSONException e) {
                        Log.e("异常", "异常" + e.toString());
                        e.printStackTrace();
                    }

                    break;

                case 5:

                    try {

                        Log.e("异常", "异常fdsfasffa" + msg.obj.toString());
                        JSONObject object = new JSONObject(msg.obj.toString());
                        JSONArray data = object.getJSONArray("data");
                        Gson g = new Gson();

                        for (int i = 0; i < data.length(); i++) {

                            JSONObject jsonObject = data.getJSONObject(i);
                            MallGoods gc = g.fromJson(jsonObject.toString(), MallGoods.class);
                            r_Goods.add(gc);

                        }

                        r_mgAdapter.setListAndNotifyDataSetChanged(r_Goods);

                    } catch (JSONException e) {
                        Log.e("异常", "异常" + e.toString());
                        e.printStackTrace();
                    }

                    break;

            }

        }
    };

    public void getGroup() {

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(null)));
        params.put("token", MySharedPreferences.getInstance(TwoFragment.this.getContext()).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(TwoFragment.this.getContext()).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getGroup");
        params.put("data[]", "");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/mall/", params, handler, 1, 404);

    }

    public void getCarousel() {

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(null)));
        params.put("token", MySharedPreferences.getInstance(TwoFragment.this.getContext()).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(TwoFragment.this.getContext()).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getCarousel");
        params.put("data[]", "");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/mall/", params, handler, 3, 404);

    }

    public void getActivitys() {

        List<String> l = new ArrayList<>();
        l.add("2");
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(TwoFragment.this.getContext()).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(TwoFragment.this.getContext()).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getActivity");
        params.put("data[type]", "2");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/mall/", params, handler, 2, 404);

    }
    public void getActivity_r() {

        List<String> l = new ArrayList<>();
        l.add("1");
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(TwoFragment.this.getContext()).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(TwoFragment.this.getContext()).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getActivity");
        params.put("data[type]", "1");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/mall/", params, handler, 5, 404);

    }
    public void getIndex() {

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(null)));
        params.put("token", MySharedPreferences.getInstance(TwoFragment.this.getContext()).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(TwoFragment.this.getContext()).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getIndex");
        params.put("data[]", "");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/mall/", params, handler, 4, 404);

    }

    //签名
    public String sing(List<String> list) {

        StringBuilder requestparams = new StringBuilder();

        requestparams.append(MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.uid, "") +
                MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.role, "") +
                System.currentTimeMillis() / 1000 + MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.password, ""));

        if (list != null) {
            for (String s : list) {
                requestparams.append(s);
            }
        }
        return requestparams.toString();
    }


    @Override
    public void onClick(View view) {

        Intent intent = new Intent();

        switch (view.getId()) {
            case R.id.logo:

                intent.setClass(this.getContext(), OrderManagementActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("logo", "0");
                intent.putExtras(bundle);
                startActivity(intent);

                break;

            case R.id.message_button:

                intent.setClass(this.getContext(), ShoppingCartActivity.class);
                startActivity(intent);

                break;

            case R.id.goods_image_a:

                Intent intenta = new Intent(this.getActivity(), GoodsDetailsActivity.class);
                intenta.putExtra("goods_id", image_id_a + "");
                startActivity(intenta);

                break;
            case R.id.goods_image_b:

                Intent intentb = new Intent(this.getActivity(), GoodsDetailsActivity.class);
                intentb.putExtra("goods_id", image_id_b + "");
                startActivity(intentb);

                break;
            case R.id.goods_image_c:

                Intent intentc= new Intent(this.getActivity(), GoodsDetailsActivity.class);
                intentc.putExtra("goods_id", image_id_c + "");
                startActivity(intentc);

                break;

        }

    }
}